/*
 *     This file is part of Mobile GPS Logger.
 * 
 *     Mobile GPS Logger is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 * 
 *     Mobile GPS Logger is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License v3 for more details.
 * 
 *     You should have received a copy of the GNU General Public License v3
 *     along with Mobile GPS Logger. If not, see <http://www.gnu.org/licenses/>.
 */


package cx.ath.skyflyer.gpslog;

import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 *
 * @author Ahti Legonkov
 */
public final class Configuration {

    /**
     * @return directory that the log files are written to.
     */
    public static String getLogPath() {
        return System.getProperty("fileconn.dir.memorycard") + "gps/";
    }

    /**
     * @return true if logging is to be started immediately after establishing
     * Bluetooth connection, false if user must select "Start" command to start
     * logging.
     */
    public static boolean getLoggingstartType() {
        try {
            String s = getRecordAsString(STORE_NAME, LOGGING_START_TYPE_RECORD_ID);
            return s.equalsIgnoreCase("true");
        }
        catch (Exception ex) {
            return true;
        }
    }

    /**
     *
     * @param immediately
     * @throws cx.ath.skyflyer.gpslog.ConfigurationException
     */
    public static void setLoggingStartType(boolean immediately) throws ConfigurationException {
        try {
            setRecord(String.valueOf(immediately), LOGGING_START_TYPE_RECORD_ID);
        }
        catch (Exception ex) {
            System.out.println("setLoggingStartType failed:" + ex);
            throw new ConfigurationException(ex);
        }
    }
    /**
     *
     * @return true if data points are to be shown on chart.
     */
    public static boolean getPointsOnChartVisible() {
        try {
            String s = getRecordAsString(STORE_NAME, CHART_POINTS_VISIBLE_RECORD_ID);
            return s.equalsIgnoreCase("true");
        }
        catch (Exception ex) {
            return true;
        }
    }

    public static void setPointsOnChartVisible(boolean visible) throws ConfigurationException {
        try {
            setRecord(String.valueOf(visible), CHART_POINTS_VISIBLE_RECORD_ID);
        }
        catch (Exception ex) {
            throw new ConfigurationException(ex);
        }
    }

    /**
     * @return units of measurement to use when displaying the chart.
     */
    public static String chartSpeedUnits() {
        return "km/h";
    }

    /**
     * @return url of the default GPS device.
     * @throws cx.ath.skyflyer.gpslog.ConfigurationException
     */
    public static String getDefaultGpsDeviceUrl() throws ConfigurationException {

        try {
            return getRecordAsString(STORE_NAME, Configuration.DEFAULT_DEVICE_URL_RECORD_ID);
        }
        catch (Exception ex) {
            throw new ConfigurationException(ex);
        }
    }

    /**
     * Sets the default GPS device Bluetooth URL.
     * @param url
     * @throws cx.ath.skyflyer.gpslog.ConfigurationException
     */
    public static void setDefaultGpsDeviceUrl(String url) throws ConfigurationException {

        try {
            RecordStore recordStore = RecordStore.openRecordStore(Configuration.STORE_NAME, true);
            byte[] data = url.getBytes();

            try {
                recordStore.setRecord(DEFAULT_DEVICE_URL_RECORD_ID, data, 0, data.length);
                System.out.println("Record changed");
            }
            catch (InvalidRecordIDException ex) {
                int idx = recordStore.addRecord(data, 0, data.length);
                System.out.println("Record added: "+idx);
            }
        }
        catch (RecordStoreException ex) {
            throw new ConfigurationException(ex);
        }
    }

    /**
     * Returns the name of the default GPS device.
     * @return
     * @throws cx.ath.skyflyer.gpslog.ConfigurationException
     */
    public static String getDefaultGpsDeviceName() throws ConfigurationException {
        try {
            return getRecordAsString(STORE_NAME, DEFAULT_DEVICE_NAME_RECORD_ID);
        }
        catch (Exception ex) {
            throw new ConfigurationException(ex);
        }
    }

    /**
     * Sets the name of default GPS device.
     * @param name
     * @throws cx.ath.skyflyer.gpslog.ConfigurationException
     */
    public static void setDefaultGpsDeviceName(String name) throws ConfigurationException {
        try {
            setRecord(name, DEFAULT_DEVICE_NAME_RECORD_ID);
        }
        catch (Exception ex) {
            throw new ConfigurationException(ex);
        }
    }

    /**
     *
     * @param value
     * @param recordId
     * @throws javax.microedition.rms.RecordStoreException
     */
    private static void setRecord(String value, int recordId) throws RecordStoreException {

        final byte[] valueBytes = value.getBytes();

        RecordStore recordStore = RecordStore.openRecordStore(Configuration.STORE_NAME, true, RecordStore.AUTHMODE_PRIVATE, true);

        try {
            recordStore.setRecord(recordId, valueBytes, 0, valueBytes.length);
        }
        catch (InvalidRecordIDException ex) {
            int idx = 0;
            while (recordStore.getNextRecordID() < recordId) {
                idx = recordStore.addRecord(null, 0, 0);
            }
            idx = recordStore.addRecord(valueBytes, 0, valueBytes.length);
        }

        recordStore.closeRecordStore();
    }

    /**
     *
     * @param storeName
     * @param recordId
     * @return
     * @throws javax.microedition.rms.InvalidRecordIDException
     * @throws javax.microedition.rms.RecordStoreException
     */
    private static String getRecordAsString(String storeName, int recordId)
            throws InvalidRecordIDException
                    , RecordStoreException {

        RecordStore recordStore = RecordStore.openRecordStore(storeName, true);
        byte[] data = recordStore.getRecord(recordId);
        String res = new String(data);
        return res;
    }

    public static final int DEFAULT_DEVICE_URL_RECORD_ID = 1;
    public static final int DEFAULT_DEVICE_NAME_RECORD_ID = 2;
    public static final int LOGGING_START_TYPE_RECORD_ID = 3;
    public static final int CHART_POINTS_VISIBLE_RECORD_ID = 4;

    private static final String STORE_NAME = "GpsLoggerStore";
}
